/**
 * 获取元素
 * @param {{query: Array, cb: Function}} opts
*/
function domSelector(opts) {
  let that = opts.that;
  let cb = opts.cb;
  let querys = opts.querys ? opts.querys : [];
  let json = {};
  if (querys.length > 0) {
    let query = uni.createSelectorQuery().in(that);
    for (let q in querys) {
      query.select("#" + querys[q]).boundingClientRect();
    }
    query.exec((res) => {
      for (let r in res) {
        json[res[r].id] = res[r];
      }
      cb(json);
    });
  } else {
    cb(json);
  }
}

/**
 * 跳转页面
 * @param {{ url: string, type?: ["to" | "redirect" | "tab"]}} opts
 **/
function toPage(opts) {
  opts = opts.currentTarget ? opts.currentTarget.dataset.tap : opts
  let url = opts.url;
  let success = opts.success;
  let fail = opts.fail;
  let complete = opts.complete;
  let type = opts.type || "to";
  let fn = null;
  switch (type) {
    case "to": fn = uni.navigateTo; break;
    case "skip": fn = uni.redirectTo; break;
    case "tab":
      let qs = [];
      let params = url;
      url = "/pages/index/index";
      fn = uni.reLaunch;
      for (let k in params) { qs.push(k + "=" + params[k]); }
      if (qs.length > 0) { url = url + "?" + qs.join("&"); }
      break;
  }
  fn({ url, success, fail, complete });
}

/**
 * 跳转到登录页面
 **/
function toPageLogin() {
  let url = "";
  let page = "/pages/xx";
  let pages = getCurrentPages();
  if (pages.length > 0) {
    const currentPage = pages[pages.length - 1];
    const options = currentPage.options;
    let qs = [];
    url = currentPage.route;
    for (let k in options) { qs.push(k + "=" + options[k]); }
    if (qs.length > 0) { qs = qs.join("&"); url += url.indexOf("?") < 0 ? "?" + qs : "&" + qs; }
    url = "?url=/" + encodeURIComponent(url);
    uni.redirectTo({ url: page + url });
  }
}

function urlParam(url) {
  var theRequest = {};
  var str = url ? url : location.href;
  var num = str.indexOf("?");
  if (num != -1) {
    str = str.substring(num + 1).split("&");
    for (var i = 0; i < str.length; i++) {
      theRequest[str[i].split("=")[0]] = str[i].split("=")[1];
    }
  }
  return theRequest;
}

function mathRound2(num){
  return Math.round(num * 100) / 100;
}

export default {
  domSelector,
  toPage, toPageLogin, urlParam,
  mathRound2
};
